1. 题目描述(中等难度)

[warning] 508. 出现次数最多的子树元素和

2. 解法一:使用深度优先搜索+HashMap

深度优先搜索计算出每个节点的和,存在HashMap中,HashMap统计,当前节点的值+其左子树的和+其右子树的和

class Solution {

    int max = 0;
    public int[] findFrequentTreeSum(TreeNode root) {
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();
        getNodeVal(root,map);
        for (Map.Entry<Integer, Integer> maps : map.entrySet()) {
           if(maps.getValue() == max){
               list.add(maps.getKey());
           }
        }
        int[] res = new int[list.size()];
        for(int i=0;i<list.size();i++){
            res[i] = list.get(i);
        }
        return res;
    }

    public int getNodeVal(TreeNode root, Map<Integer, Integer> map) {
        if (root == null) {
            return 0;
        }
        int left = getNodeVal(root.left, map);
        int right = getNodeVal(root.right, map);
        int ans = left + right + root.val;
        map.put(ans, map.getOrDefault(ans, 0) + 1);
        max = Math.max(max,map.get(ans));
        return ans;
    }
}

计算树节点和方法

int sum = root.val + getNodeVal(root.left) +getNodeVal(root.right);
© gaohueric all right reserved,powered by Gitbook文件修订时间: 2021-12-08 23:22:22

results matching ""

    No results matching ""